package com.alan.camunda.boot.groovymod.shelllab;

import com.alibaba.fastjson2.JSONObject;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;

import java.util.Map;

public class RealUse {

    public static void main(String[] args) {
        JSONObject data = new JSONObject();
        data.put("num1", 18);
        data.put("num2", 18);

        Binding binding = prepare(data);
        String userInputScript = """
           num1 > 18 && num2 < 18
        """;

        System.out.println(execute(binding, userInputScript));
    }

    public static String TEMPLATE_PREFIX = """
            import static com.alan.camunda.boot.util.StringFunctions.*
            def result =
            """;

    public static String TEMPLATE_SUFFIX = """
            \nreturn result
            """;

    public static Binding prepare(Map<String, Object> variables) {
        Binding binding = new Binding();
        for (Map.Entry<String, Object> entry : variables.entrySet()) {
            binding.setVariable(entry.getKey(), entry.getValue());
        }
        return binding;
    }

    public static Object execute(Binding binding, String script) {
        GroovyShell shell = new GroovyShell(binding);
        script = TEMPLATE_PREFIX + script + TEMPLATE_SUFFIX;
        Object result = shell.evaluate(script);
        return result;
    }

}
